/*!Important URLs. Must be set for new setup*/

(function () {

    /* Start of module name */
    var appForm = angular.module('applicationForm', []);
    var baseAddress = 'http://localhost:2071/api/';
    //var baseAddress = 'http://app.enrollment.api.buy-me.ph/api/';
    var url = "";
    /* End of module name */


    /* Start of Controller */
    appForm.controller('ApplicationController', function PostController($scope, ServiceFactory) {
        $scope.editMode = false;
        $scope.Home_Show = false;
        GetAll();
        $scope.Title = 'Application';
        function GetAll() {
            ServiceFactory.getFormsList().success(function (data) {
                $scope.ApplicationForms = data;
                $scope.ApplicationForms_InitiateLookUps();

            }).error(function (data) {
                $scope.error = 'Unable to load Application Forms: ' + error.message;
            });
        }
        $scope.ApplicationForms_InitiateLookUps = function () {
            $scope.ApplicationForms_GetLevels();
        };
        $scope.ApplicationForms_Get = function () {
            $scope.AppForm = this.AppForm;
            $('#AppFormModal').modal('show');
        };//Get form

        $scope.ApplicationForms_Edit = function () {

            $scope.AppForm = this.AppForm;
            $scope.editMode = true;

            var birthdate = new date($scope.AppForm.BirthDate);
            $scope.AppForm.BirthDate = birthdate.normalDate;

            $('#AppFormModal').modal('show');
        };//Edit form

        $scope.ApplicationForms_ShowAdd = function () {
            $scope.AppForm = new Applicationform();
            $scope.AppForm.RefNumber = guid();
            $scope.editMode = false;
            $('#AppFormModal').modal('show');
        };//Add form modal

        $scope.ApplicationForms_Cancel = function () {
            $scope.AppForm = null;
            $('.nav-tabs a[href="#personal"]').tab('show');
            $('#AppFormModal').modal('hide');
        };// Cancel modal

        $scope.ApplicationForms_ShowDelete = function (data) {
            $scope.ApplicationForms.Applicationform = data;
            //$scope.AppForm = new Applicationform();
            $scope.deleteForm = true;
            $('#confirmModal').modal('show');
        };//Add form modal

        $scope.ApplicationForms_Delete = function () {
            currentForm = $scope.ApplicationForms.Applicationform;
            $('#confirmModal').modal('show');

            ServiceFactory.deleteForm(currentForm).success(function (data) {
                $('#confirmModal').modal('hide');

                ReloadData();
                function ReloadData() {
                    ServiceFactory.getFormsList().success(function (data) {
                        $scope.ApplicationForms = data;
                        $scope.ApplicationForms_InitiateLookUps();

                    }).error(function (data) {
                        $scope.error = 'Unable to load Application Forms: ' + error.message;
                    });
                }

            }).error(function (data) {
                $scope.error = "An Error has occured while Deleting item! " + data.ExceptionMessage;

                $('#confirmModal').modal('hide');
            });
        };// delete item

        $scope.ApplicationForms_Add = function () {

            $scope.AppForm.BirthDate = txtBdate.value;
            var currentForm = $scope.AppForm;
            currentForm.CreatedBy = "espirituj"; //TODO: Create a globel current user account handler

            if ($scope.addform.$valid) {
                ServiceFactory.addForm(currentForm).success(function (data) {
                    $scope.addMode = false;
                    currentForm.editMode = false;
                    alert('Item saved.');
                    $scope.AppForm = null;//reset form
                    $scope.ApplicationForms = null;

                    $('.nav-tabs a[href="#personal"]').tab('show');
                    $scope.ApplicationForms_Cancel();
                    ReloadData();
                    function ReloadData() {
                        ServiceFactory.getFormsList().success(function (data) {
                            $scope.ApplicationForms = data;
                            $scope.ApplicationForms_InitiateLookUps();

                        }).error(function (data) {
                            $scope.error = 'Unable to load Application Forms: ' + error.message;
                        });
                    }

                }).error(function (data) {
                    $scope.AppForm.error = "An Error has occured while creating this form! " + data.ExceptionMessage;
                });
            }
            else {
                $scope.AppForm.error = "There are invalid fields.";

                //var $errDlg = $("#errorDialog");
                //$errDlg.removeClass('alert alert-danger alert-dismissible ng-hide');
                //$errDlg.toggleClass('alert alert-danger alert-dismissible ng-show');
                //errorMessage.text('There are invalid fields');
            }

        };// add form data
        $scope.ApplicationForms_Update = function () {
            var currentForm = this.AppForm;
            currentForm.BirthDate = txtBdate.value;
            ServiceFactory.updateForm(currentForm).success(function (data) {
                currentForm.editMode = false;

                $('#AppFormModal').modal('hide');
            }).error(function (data) {
                $scope.error = "An Error has occured while updating form! " + data.ExceptionMessage;
            });
        };
        $scope.ApplicationForms_ShowConfirm = function (data) {
            $scope.AppForm = data;
            $('#confirmModal').modal('show');
        };//updates form data

        $scope.ApplicationForms_GetLevels = function () {
            ServiceFactory.getLevelList().success(function (data) {
                $scope.Levels = {};
                var DateToday = new Date();

                if (data.length == 0) {
                    data = [{
                        "StudentLevel": "Grade 1",
                        "Description": "Grade 1",
                        "CreatedDate": DateToday,
                        "CreatedBy": "System",
                        "ModifiedDate": null,
                        "ModifiedBy": null,
                        "Remarks": null
                    }];
                }
                $scope.Levels.SchoolLevels = data;

            }).error(function (data) {
                $scope.error = 'Unable to load levels: ' + error.message;
            });
        }; //get student levels

        //TODO:Sorting

    });


    /* End of controller */


    /* Start of Service factory */

    //Application form factory

    appForm.factory('ServiceFactory', function ($http) {
        return {
            getFormsList: function () {
                url = baseAddress + "applicationform/GetFormsList";
                return $http.get(url);
            },
            getForm: function (AppForm) {
                url = baseAddress + "applicationform/GetForm/" + AppForm.RefNumber;
                return $http.get(url);
            },
            deleteForm: function (AppForm) {
                //url = baseAddress + 'applicationform/DeleteForm/' + form.ID;
                //return $http.delete(url);
                return $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: baseAddress + 'applicationform/DeleteForm/' + AppForm.ID,
                    data: AppForm,
                });
            },
            addForm: function (AppForm) {
                //ajax is readable by jobject if dotnet
                return $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: baseAddress + 'applicationform/AddForm/',
                    data: AppForm,
                });
            },

            updateForm: function (AppForm) {
                //ajax is readable by jobject if dotnet
                return $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: baseAddress + 'applicationform/UpdateForm/' + AppForm.ID,
                    data: AppForm,
                });
            },
            //url = baseAddress + "UpdateForm/" + form.ID;
            //return $http.put(url); Boom! not working,..   

            getLevelList: function (Levels) {
                url = baseAddress + "level/Get/";
                return $http.get(url);
            }
        };
    });

    /* End of Service Factory*/

    function guid() {
        function s4() {
            return Math.floor((1 + Math.random()) * 0x10000)
              .toString(16)
              .substring(1);
        }
        return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
          s4() + '-' + s4() + s4() + s4();
    }

})();
